package main;


import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

import main.states.GameStateManager;

public class GamePanel extends JPanel implements Runnable, KeyListener{

	private static final long serialVersionUID = 1L;
		// dimensions
		public static final int WIDTH = 960;
		public static final int HEIGHT = 640;

		//thread
		public static final int FPS = 60;
		public Thread thread;
		public boolean running;
		//Graphics
		public Graphics2D g;
		public GameStateManager gsm;
		public BufferedImage panel;
		
		public GamePanel(){
			super();
            setPreferredSize(new Dimension(WIDTH, HEIGHT));
            setFocusable(true);
			this.gsm = new GameStateManager();
			this.running = false;
		}
		
		public void addNotify() {
			super.addNotify();
			if(thread == null ) {
				addKeyListener(this);
				thread = new Thread(this);
				thread.start();
			}
		}
		
		public void init() {
			panel = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
			g = (Graphics2D) panel.getGraphics();
			
			running = true;

		}
		

		@Override
		public void run() {
			init();
			int targetTime = 1000/FPS;
			long start, elapsed, wait;
			
			while(running){
				
				start = System.nanoTime();
				update();
				draw();
				drawToScreen();
				
				elapsed = (System.nanoTime() - start)/1000000;
				
				wait = targetTime - elapsed;
				if(wait < 0) wait = 5;
                
                try {
                        Thread.sleep(wait);
                }
                catch(Exception e) {
                        e.printStackTrace();
                }
				
			}
			
		}
		
		private void draw(){
			gsm.draw(g);

		}
		
		private void drawToScreen() {
			Graphics g2 = getGraphics();
			g2.drawImage(panel, 0,0, null);	

			
		}


		private void update() {
			gsm.update();					
		}

		@Override
		public void keyPressed(KeyEvent k) {
			gsm.keyPressed(k.getKeyCode());			
		}

		@Override
		public void keyReleased(KeyEvent k) {
			gsm.keyReleased(k.getKeyCode());					
		}

		@Override
		public void keyTyped(KeyEvent k) {
			// TODO Auto-generated method stub
			
		}
}

